(function($,_window){
     var smartpost=function(refreshFun){
    	 this._init();
         this.refreshFun=refreshFun;
     };
     _window.smartpost=smartpost;
     smartpost.prototype._init=function(){
    	 this.loadGroups();
    	 this.loadRequestEntities();
    	 this.loadScene();
         this.loadEnv();
     }
     smartpost.prototype.loadGroups=function(){
    	 var me = this;
    	 this.load("group",function(data){
    		 me.group=data;
    	 });
     };
     smartpost.prototype.loadEnv= function () {
         var me = this;
         this.load("env",function(data){
             me.env=data;
         });
     }
     smartpost.prototype.loadRequestEntities=function(){
    	 var me = this;
    	 this.load("entity",function(data){
    		 me.entities=data;
    	 });
     };
     smartpost.prototype.getEnvDetial=function(id){
         return this.env[id];
     }
     smartpost.prototype.loadScene=function(){
    	 var me = this;
    	 this.load("scene",function(data){
    		 me.scene=data;
    	 });
     };
     smartpost.prototype.load=function(type,callback){
    	$.ajax({
    		url:"processor.htm",
    		data:{type:type,action:"load"},
    		type:"POST",
    		async:false,
    		dataType:"json",
    		success:function(data){
    			callback(data);
    		}
    	});
     };
    smartpost.prototype.getCookie=function(cookieName){
        if(document.cookie.length>0){
            var cookies = document.cookie;
            var c_start = cookies.indexOf(cookieName+"=");
            if(c_start>=0){
                c_start=c_start+cookieName.length+1;
                var c_end=cookies.indexOf(";",c_start);
                if (c_end==-1) c_end=cookies.length;
                return unescape(cookies.substring(c_start,c_end))
            }else{
                return "";
            }
        }
        return "";
    }
    smartpost.prototype.checkLogin=function(){
        var isRoot = this.getCookie("isRoot");
        if(isRoot==true||isRoot=='true'){
            return true;
        }else{
            return false;
        }
    }
     smartpost.prototype.permission=function(password,isLogined,callback){
         $.ajax({
             url:"login.htm",
             data:{password:password,isLogined:isLogined},
             type:"POST",
             error:function(t,e){
                 console.log("request server error ")
                 console.log(t);
                 console.log(e);
                 var errorDialog = new dialog({
                     content:"请求后端服务异常，请查查看后端日志！"
                 });
                 callback(false);
             },
             success:function(data){
                 if(!data.status){
                     callback(false);
                 }else{
                     callback(true);
                 }
             }
         });
     }
     smartpost.prototype.save=function(type,data,callback){
         if(!this.checkLogin()){
             var errorDialog = new dialog({
                 content:"权限不够，必须Root用户才可以编辑！"
             });
             errorDialog.open();
             return ;
         }
         var me = this;
    	 $.ajax({
     		url:"processor.htm",
     		data:{type:type,action:"save",data:data},
     		type:"POST",
            error:function(t,e){
              console.log("request server error ")
              console.log(t);
              console.log(e);
              var errorDialog = new dialog({
                 content:"请求后端服务异常，请查查看后端日志！"
              });
              errorDialog.open();
            },
     		datatype:"json",
     		success:function(data){
                if(!data.status){
                    if(callback){
                        callback(data);
                        return ;
                    }
                    var errorDialog = new dialog({
                        content:data.error,
                        onOk:function(){
                            if(me.refreshFun){
                                me.refreshFun();
                            }
                        }
                    });
                    errorDialog.open();
                    return ;
                }else{
                    if(callback){
                        callback(data);
                        return ;
                    }
                    var successDialog = new dialog({
                        title:"提示",
                        content:"操作成功！",
                        onOk:function(){
                            if(me.refreshFun){
                                me.refreshFun();
                            }
                        }
                    });
                    successDialog.open();
                    return ;
                }
            }
     	});
     };
   
     smartpost.prototype.getGroupDetails=function(collectionId){
    	 var entities = [];
         for(var pro in this.entities){
             var item = this.entities[pro];
             if(item.group==collectionId){
                 entities.push(item);
             }
         }
    	 return entities;
     };
     smartpost.prototype.getRequestEntity=function(entityId){
    	 return this._copyObject(this.entities[entityId]);
     };
    
    smartpost.prototype._copyObject=function(object){
        if(this._isArray(object)){
            var copy=[];
            for(var i=0;i<object.length;i++){
                if(this._isObject(object[i])){
                    copy.push(this._copyObject(object[i]));
                }else{
                    copy.push(object[i]);
                }
            }
            return copy;
        }else if(this._isObject(object)){
            var copy={};
            for(var key in object){
                if(this._isObject(object[key])){
                    copy[key]=this._copyObject(object[key]);
                }else if(object.hasOwnProperty(key)){
                    copy[key]=object[key];
                }
            }
            return copy;
        }
    }
    smartpost.prototype._isArray=function(object){
        if(object&&typeof object==='object'&&object.constructor===Array){
            return true;
        }
        return false;
    }
    smartpost.prototype._isObject=function(object){
        if(object&&typeof object==='object'){
            return true;
        }
        return false;
    }
     
     smartpost.prototype.getSceneDetails=function(sceneId){
    	 var sceneDetails = this.scene[sceneId];
    	 return sceneDetails;
     };
    /**
     * {envName:global/ke,items:[],id:xxxx}
     * @param env
     */
     smartpost.prototype.saveEnv=function(env,callback){
         if(!this.env){
             this.env={};
         }
         if(!env.id|| $.trim(env.id)==''){
             env.id=Math.uuid();
         }
         for(var pro in this.env){
             if(env.envName==this.env[pro].envName&&env.id!=this.env[pro].id){
                 if(callback){
                     callback({status:false,error:"【"+env.envName+'】环境已经存在，不能重复添加！'})
                 }
                 return ;
             }
         }
         this.env[env.id]=env;
         this.save("env",JSON.stringify(this.env),callback);
     }

    smartpost.prototype.removeEnv=function(id){
        if(this.env){
            this.env[id]=undefined;
            this.save("env",JSON.stringify(this.env));
        }
    }
     
     smartpost.prototype.saveRequestEntity=function(entity,callback){
    	 if(!entity.entityId){
    		 entity.entityId=Math.uuid();
    	 }
         for(var pro in this.entities){
             if(this.entities[pro].name==entity.name&&this.entities[pro].entityId!=entity.entityId){
                 var errorDialog = new dialog({
                     content:"【"+entity.name+"】请求实体已存在，不能重复添加！"
                 });
                 errorDialog.open();
                 return ;
             }
         }
         if(!this.entities){
             this.entities={};
         }
    	 this.entities[entity.entityId]=entity;
    	 this.save("entity", JSON.stringify(this.entities));

     };
     
     smartpost.prototype.saveScene=function(scene){
    	 if(!scene.sceneId){
    		 scene.sceneId=Math.uuid();
    	 }
         for(var pro in this.scene){
             if(this.scene[pro].name==scene.name&&this.scene[pro].sceneId!=scene.sceneId){
                 var errorDialog = new dialog({
                     content:"【"+scene.name+"】场景已经存在，不能重复添加！"
                 });
                 errorDialog.open();
                 return ;
             }
         }
         if(!this.scene){
             this.scene={};

         }

    	 this.scene[scene.sceneId]=scene;
    	 this.save("scene", JSON.stringify(this.scene));
     };


     smartpost.prototype.saveGroup=function(group,callback){
    	 if(!group.groupId){
    		 group.groupId=Math.uuid();
    	 }
         for(var pro in this.group){
             if(this.group[pro].name==group.name&&this.group[pro].groupId!=group.groupId){
                 var errorDialog = new dialog({
                     content:"【"+group.name+"】分组已存在，不能重复添加！"
                 });
                 errorDialog.open();
                 return ;
             }
         }
         if(!this.group){
             this.group={};
         }

    	 this.group[group.groupId]=group;
    	 this.save("group", JSON.stringify(this.group),callback);
     };
     
     smartpost.prototype.deleteScene=function(sceneId){
    	 this.scene[sceneId]=undefined;
    	 this.save("scene", JSON.stringify(this.scene));
     };
    
     smartpost.prototype.deleteRequestEntity=function(entityId,callback){
         var oldEntity = this.entities[entityId];
    	 this.entities[entityId]=undefined;
    	 this.save("entity", JSON.stringify(this.entities));
        var group = this.group[oldEntity.group];
        var containEntities = group.containEntities;
        var newContainEntities=[];
        for(var i=0;i<containEntities.length;i++){
            if(containEntities[i]!=oldEntity.entityId){
                newContainEntities.push(containEntities[i]);
            }
        }
        group.containEntities=newContainEntities;
        this.saveGroup(group);
     };
    
     smartpost.prototype.deleteGroup=function(groupId){
    	 this.group[groupId]=undefined;
    	 this.save("group", JSON.stringify(this.group));
     };

    smartpost.prototype.invokeRequest=function(requestParam,callback){
        var entity;
        if(typeof  requestParam=='string'){
            entity= this.entities[requestParam];
        }else{
            entity=requestParam;
        }
        $.ajax({
            url:"invokeRequest.htm",
            type:"post",
            data:{entityJSON:JSON.stringify(entity)},
            dataType:"json",
            success:function(data){
                callback(data);
            }
        });
    }

    smartpost.prototype.getBatchInvokeResult=function(invokeId,intervalTime,callback,isFirst){
        var me = this;
        var handle = setTimeout(function(){
            $.ajax({
                url:"queryInvokeResult.htm",
                type:"post",
                dataType:"json",

                error:function(e,a){
                    console.log(a)
                    //me.getBatchInvokeResult(invokeId,intervalTime,callback,false);
                },
                data:{invokeId:invokeId},
                success:function(data){
                    if(data.status){
                        var result = data.data;
                        callback(data.data);
                        clearTimeout(handle)
                    }else{
                        me.getBatchInvokeResult(invokeId,intervalTime,callback,false);
                    }
                }
            });
        },isFirst?0:intervalTime);
    }
    smartpost.prototype.batchInvoke=function(requestEntities,callback){
        var me = this;
        $.ajax({
            url:"batchInvoke.htm",
            type:"post",
            data:{entityArray:JSON.stringify(requestEntities)},
            dataType:"json",
            success:function(data){
                 if(data.status){
                    for(var j=0;j<requestEntities.length;j++){
                        var count=0;
                        var entity = requestEntities[j];
                        if(entity.invokeTime){
                            var time = parseInt(entity.invokeTime);
                            for(var i=0;i<time;i++){
                                count++;
                                var intervalTime=1000;
                                if(entity.intervalTime){
                                    intervalTime+=parseInt(entity.intervalTime);
                                }
                                me.getBatchInvokeResult(data.invokeId,intervalTime,callback,true);
                            }
                        }
                    }
                 }else{
                     var errorDialog = new dialog({
                        content:data.error
                     });
                     errorDialog.open();
                     return ;
                 }
            }
        });
    }

}
)($,window);

 